// INIT VARIABLES - SMARTY
var CURRENCY_SYMBOL = '￥';

if (jQuery.validator) {
	var error_msg = [];
	  jQuery.validator.setDefaults({
		debug: false,
	    errorClass: 'has-error',
	    validClass: 'has-success',
	    ignore: "",
	    highlight: function (element, errorClass, validClass) {
	      $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
	      if ($.inArray($(element).closest('.row.form').attr('data-error'), error_msg) < 0 ) {
	    	  error_msg.push($(element).closest('.row.form').attr('data-error'));
		   };
		   if (error_msg.toString()) {
			   	$('#form-error-msg').html(error_msg.toString().replace(',', '<br>') );
		      	$('#form-error').slideDown();
				setTimeout(function(){
					$('#form-error').slideUp();
		    	},10000);
		    }
	    },
	    unhighlight: function (element, errorClass, validClass) {
	      $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
	      $(element).closest('.form-group').find('.help-block').text('');
	    },
	    errorPlacement: function (error, element) {
	    	$(element).closest('div').find('.help-block').html(error);
	    },
	    submitHandler: function (form) {
	    	 var formID = $(form).attr('id');
	    	 var formCheck = $(form).attr('data-attr-id');
	    	 if(formCheck == undefined || formCheck == ""){
	    		 formCheck = $(form).attr('id');
	    	 }
	    	 switch ( formCheck ) {
	    	 	case 'Edit_Record':
	          	case 'select-class-form':
	          	case 'add-member-form':
	          	case 'student-form':
	          	case 'product-form':
	          	case 'additional-form':
	          	case 'payment-form':
	          	case 'member-form':
	          	case 'update-student':
	          	case 'send-email-form':
	          	case 'reset-cart-form':
	          	case 'delete-member-form':
	          	case 'add-note-form':
	          	case 'edit-warning-form':
	          	case 'move-enrolment-form':
	          	case 'make-up-form':
	          	case 'move-trial-form':
	          	case 'customProduct-form':
	          	case 'class-form':
	          	case 'search-classes-form-new':
	          	case 'search-classes-form-move':
	          	case 'search-classes-form-makeup':
	          	case 'search-classes-form-move-trial':
	          	case 'FilterClassesList-form':
	          	case 'FilterClassesDropdown-form':
	          	case 'send-email-classes-form':
	          	case 'attendance-roll-form':
	          	case 'SaveAttendance-form':
	          	case 'WalkIn-form':
	          		SubmitForm(formID, formCheck)
	          		break;
	        	
	          	case 'filter-orders-form':
	          		getOrdersFiltered();
	          		break;
	          		
	          	default:
	          		form.submit();
	          }
	    }
	  });
	  var duplicated_id;
	  var messageFunc = function () { 
		if (duplicated_id) {
			return "This email address is already being used. <a href='javascript:void(0)' onclick='window.location.assign(\"/admin/members/new/"+duplicated_id+"\")'>Click here to load existing member</a>";
		}
		return "This email address is already being used."; 
	};
		
	jQuery.validator.addMethod(
  		"uniqueEmail", 
  		function(value, element, params) {
  			var response = false;
  			var idVal = params.id;  	
  	  	  	if(params.field) idVal = $(params.field).val();
  	  	  	
  			$.ajax({
  				type: "POST",
  			    url: "/admin/includes/processes/checkEmail.php",
  				cache: false,
  				async: false,
  				data: "username="+value+"&id="+idVal+"&table="+params.table,
  				dataType: "json",
  			    success: function(res, textStatus) {
  			    	try{
  			    		if ( res.email ) {
  			    			response = false;
	  			    	} else {
		  			    	response = true;
		  			    }
  			    		if(params.table == 'user') duplicated_id = res.existing_id;
  			    	}catch(err){ }
  			    }
  			});
  			return response;
  			
		}, messageFunc
	);

	jQuery.validator.addMethod(
	  		"uniqueURL", 
	  		function(value, element, params) {
	  			var response = false;
	  			$.ajax({
	  				type: "POST",
	  			    url: "/admin/includes/processes/urlencode.php",
	  				cache: false,
	  				async: false,
	  				data: "value="+encodeURIComponent(value)+"&id="+params.id+"&idfield="+params.idfield+"&table="+params.table+"&field="+params.field+"&field2="+params.field2+"&value2="+$('#'+params.value2).val(),
	  				dataType: "json",
	  			    success: function(res, textStatus) {
	  			    	try{
	  			    		if ( res.duplicated ) {
	  			    			response = false;
		  			    	} else {
			  			    	response = true;
			  			    }
	  			    	}catch(err){ }
	  			    }
	  			});
	  			return response;
	  			
			}, 
			"Invalid URL: It's currently being used or has non-alphanumeric characters."
		);
		


		jQuery.validator.addMethod(
		  		"double", 
		  		function(value, element) {
		  			if ($.isNumeric(value) || value =='') {
		  				return true;
		  			} 
		  			return false;
				}, 
				"Invalid value. Must be numeric."
		);

		jQuery.validator.addClassRules({
			double: {
				double: true
			},
			number: {
				number: true,
				digits: true,
				maxlength: 4
			},
		});
}


function SubmitForm(formID, formCheck){
	var confirmation = $('#'+formID).attr('data-confirm');
	if( confirmation == undefined || confirmation == "" || confirm(confirmation)){
		$('body').css('cursor', 'wait'); console.log(formID +' | '+formCheck);
		$('#'+formID).find('.btn').addClass('disabled');
		var datastring = $('#'+formID).serialize();
		var action_url = $('#'+formID).find('input[name="url"]').val();
		if(formID == 'Edit_Record'){
    		var callbackFn = $('#'+formID).attr('data-callback');
			action_url = "/admin/includes/processes/processes-record.php";
		}
		if(action_url == undefined || action_url == ""){
			action_url = "/admin/includes/processes/processes-enrolment.php";
		 }
		
		$.ajax({
			type : "POST",
			url : action_url,
			cache : false,
			async: false,
			data : datastring,
			dataType : "json",
			success : function(obj, textStatus) {
				try {
					if(formID == 'Edit_Record'){
						var notice = obj.notice;
    				 	$('.notification').hide();
    				 	$('#'+ notice).slideDown();
    					setTimeout(function(){
    						$('#'+ notice).slideUp();
    			    	},10000);
	    			    if(obj.IDs){
	    					$.each(obj.IDs, function(k, v) {
	    					    if(v) $('input[name="'+k+'"]').val(v);
	    					});
	    			    }
	    			    if(callbackFn){
							var fn = window[callbackFn];
		    			if (typeof fn === "function") fn();
						} 
					}
					
					if (obj.error) {
				 		$('#'+formID).find('.error-alert').find('strong').html(obj.error);
				 		$('#'+formID).find('.error-alert').fadeIn('slow'); 
				 		if(obj.javascript){
				 			eval(obj.javascript);
				 		}
				 		if(formID =='payment-form'){
				 			$('#step6-btn').show();
				 			$('#processing-div').hide();
				 		}
				 	} else if (obj.success){
				 		$('#'+formID).find('.error-alert').hide(); 
				 		switch (formCheck) {
				 				
					 		case 'search-classes-form-move':
				          	case 'search-classes-form-new':
				          	case 'search-classes-form-makeup':
				          	case 'search-classes-form-move-trial':
			          			$('#'+formCheck+'-result').html(obj.template).closest('form').find('.classterm-btns').show();
			          			break;
			          			
				          	case 'select-class-form': 
				          		$('#accordion').find('.collapse.in').removeClass('in');
						 		$('.step2').collapse('show');
						 		$('#unchecked-step1').hide();
						 		$('#checked-step1').show();
						 		$('#cart-summary').html(obj.shoppingcart);
						 		$('.enrolment-lbl').hide();
						 		$('#enrolment-lbl-' + $('#enrolment').val() ).show();
						 		$('html,body').animate({
				        			scrollTop : $('#enrolment-wrapper').offset().top
				        		});
				          		break;
				          		
				        	case 'add-member-form':
				        		$('#accordion').find('.collapse.in').removeClass('in');
						 		$('.step3').collapse('show');
						 		$('#unchecked-step2').hide();
						 		$('#checked-step2').show();
						 		$('#student-form-wrapper').show();
						 		$('#cart-summary').html(obj.shoppingcart);
						 		$('#student-wrapper').html(obj.studentTemplate);
						 		$("#cnt").val(obj.cnt); 
						 		$('html,body').animate({
				        			scrollTop : $('#enrolment-wrapper').offset().top
				        		});
				        		break;
				        		
				        	case 'student-form':
				        		$('#accordion').find('.collapse.in').removeClass('in');
						 		if(obj.trial){
						 			$('.step6').collapse('show');
							 		$('#payment-wrapper').show();
							 		if($('#ccname').val() == '') $('#ccname').val($('#gname').val() +' '+ $('#surname').val());
							 		$('.not-trial').hide();
							 		setCCRequired(false);
						 		}else{
						 			$('.step4').collapse('show');
						 		}
						 		$('html,body').animate({
				        			scrollTop : $('#enrolment-wrapper').offset().top
				        		});
						 		
						 		$('#unchecked-step3').hide();
						 		$('#checked-step3').show();
						 		$('#cart-summary').html(obj.shoppingcart);
						 		$('.delete-student-btn').show();
						 		$.each(obj.remove, function(id, value){
			                     	$('#student'+value).html('');
							 	});
				        		break;	
				        		
				        	case 'product-form':
				          	case 'class-form':
				        		$('#cart-summary').html(obj.shoppingcart);
				        		var response = obj.response;
				        		if(response){
				        			$('#payment-amount').val(obj.charge.toFixed(2));
							 		$('#payment-amount').attr('data-amount',obj.charge.toFixed(2));
							 		$('.payment-amount').val(obj.charge.toFixed(2)).html(obj.charge.toFixed(2));
							 		CheckPaymentRequired();
					        		$('#notification').hide();
					        		$('#edited').find('b').html(response);
					        		$('#edited').slideDown();
			    					setTimeout(function(){
			    						$('#edited').slideUp();
			    			    	},5000);
				        		}
				        		break;
				        		
				        	case 'additional-form':
				        	case 'customProduct-form':
				        		$('#payment-wrapper').show();
				        		if($('#ccname').val() == '') $('#ccname').val($('#gname').val() +' '+ $('#surname').val());
				        		$('#payment-amount').val(obj.charge.toFixed(2));
						 		$('#payment-amount').attr('data-amount',obj.charge.toFixed(2));
						 		$('.payment-amount').val(obj.charge.toFixed(2)).html(obj.charge.toFixed(2));
						 		CheckPaymentRequired();
						 		$('#accordion').find('.collapse.in').removeClass('in');
						 		$('#cart-summary').html(obj.shoppingcart);
						 		CheckPaymentMethod();
						 		CheckPaymentRequired();
						 		var hasError = false;
						 		$('.error-alert').each(function(){
						 			if($(this).css('display') != 'none') {
						 				hasError = true;
						 				$(this).closest('.panel-collapse').collapse('show');
						 			}
						 		});
						 		if(!hasError) { $('.step6').collapse('show'); }
						 		$('#unchecked-step5').hide();
						 		$('#checked-step5').show();
						 		$('html,body').animate({
				        			scrollTop : $('#enrolment-wrapper').offset().top
				        		});
				        		break;
				        		
				        	case 'payment-form':
				        		$('#payment-wrapper').html(obj.template);
						 		$('#unchecked-step6').hide();
						 		$('#checked-step6').show();
						 		$('a[data-parent="#accordion"]').attr('data-toggle','');
				        		break;
				        		
				        	case 'member-form':
				        	case 'update-student':
				        	case 'reset-cart-form':
				        	case 'delete-member-form':
				        		if(obj.url) {
				        			window.location.assign(obj.url);
				        		}else{
				        			location.reload();
				        		}
				        		break;
	
				          		
				        	case 'send-email-form':
				        		$('#table-emails-wrapper').html(obj.template);
				          		$('#'+formID).closest('.form-wrapper').hide('slow');
				          		$('#'+formID).find('.remove-content').val('');
				          		$('.emails-content').show('slow');
				          		$('#sent').find('b').html(obj.success);
						 		$('#sent').slideDown();
						 		setTimeout(function(){
									$('#sent').slideUp();
						    	},10000);
						 		break;
				        	
				        	case 'add-note-form':
				          		$('#table-notes-wrapper').html(obj.template);
				          		$('#'+formID).closest('.form-wrapper').hide('slow');
				          		$('#'+formID).find('.remove-content').val('');
				          		$('.notes-content').show('slow');
				          		$('#sent').find('b').html(obj.success);
						 		$('#sent').slideDown();
						 		setTimeout(function(){
									$('#sent').slideUp();
						    	},10000);
						 		break;
						 		
				        	case 'edit-warning-form':
				        		$('#warning-content-wrapper').html(obj.template);
				          		$('#'+formID).closest('.form-wrapper').hide('slow');
				          		if(obj.warning){
				          			$('#member-summary').addClass('bg-red');
				          			$('#warning-nav-tab').addClass('bg-red');
				          			$('#warning-content-wrapper').html(obj.warning);
				          		}else{
				          			$('#member-summary').removeClass('bg-red');
				          			$('#warning-nav-tab').removeClass('bg-red');
				          			$('#warning-content-wrapper').html('This member does not have any warnings.');
				          		}
				          		$('.warning-content').show('slow');
				          		$('#sent').find('b').html(obj.success);
						 		$('#sent').slideDown();
						 		setTimeout(function(){
									$('#sent').slideUp();
						    	},10000);
				        		break;
				        		
				        	case 'move-enrolment-form':
				        	case 'make-up-form':
				        	case 'move-trial-form':
				        		$('#studentclass-wrapper-'+obj.studentID).html(obj.template);
				          		$('#'+formID).closest('.form-wrapper').hide('slow');
				          		$('#student-classes-content').show('slow');
				          		$('#sent').find('b').html(obj.success);
						 		$('#sent').slideDown();
						 		setTimeout(function(){
									$('#sent').slideUp();
						    	},10000);
				        		break;
				        	
				        	case 'send-email-classes-form':
				          		$('#sent').find('b').html(obj.success);
				          		$('#'+formID).find('.remove-content').val('');
						 		$('#sent').slideDown();
						 		setTimeout(function(){
									$('#sent').slideUp();
						    	},10000);
						 		break;

				          	case 'FilterClassesList-form':
				          		if(obj.template) $('#classterms-wrapper').hide().html(obj.template).show('slow');
				          		break;
				          		
				          	case 'FilterClassesDropdown-form':
				          		if(obj.template) $('#attendance-form-wrapper').hide().html(obj.template).show('slow');
				          		break;
				          		
				          	case 'attendance-roll-form':
				          		if(obj.template) $('#attendance-roll-wrapper').hide().html(obj.template).show('slow');
				          		$('html,body').animate({
				        			scrollTop : $('#attendance-roll-wrapper').offset().top
				        		});
				          		break;
				          		
				          	case 'SaveAttendance-form':
				          		$('#edited').find('b').html(obj.message);
						 		$('#edited').slideDown();
						 		setTimeout(function(){
									$('#edited').slideUp();
						    	},10000);
				          		break;
				          		
				          	case 'WalkIn-form':
				          		$('.clear-saved').val('');
						 		$('#sent').slideDown();
						 		setTimeout(function(){
									$('#sent').slideUp();
						    	},10000);
				          		break;
				          		
			          }
				 	}
					$('#'+formID).find('button[type="submit"]').removeAttr('disabled');
					$('#step6-btn').removeAttr('disabled');
				} catch (err) {}
				$('body').css('cursor', 'default');
				$('#'+formID).find('.btn').removeClass('disabled');
				$('#'+formID).find('button[type="submit"]').removeAttr('disabled');
				$('#step6-btn').removeAttr('disabled');
			},
			error: function(jqXHR, textStatus, errorThrown){
				$('body').css('cursor','default'); 
				$('#'+formID).find('.btn').removeClass('disabled');
				alert(textStatus+': '+errorThrown);
				console.log('AJAX error:'+errorThrown);
		  }
		});
	}
}


function deleteItem(ID){
	if (ConfirmDelete()) {
		$('body').css('cursor','wait');
		$( '#cartitem'+ ID ).fadeTo( "fast", 0.5 );
		var frmTkn = $("#formToken").val();
		$.ajax({
			type: "POST",
		    url: "/admin/includes/processes/processes-enrolment.php",
			cache: false,
			data: 'action=DeleteItem&cartitem_id='+ID+'&formToken='+frmTkn,
			dataType: "json",
		    success: function(obj) {
		    	try{
		    		if (obj.error) {
		    			$( '#cartitem'+ ID ).fadeTo( "fast", 1 ); 
		    			alert('Item cannot be deleted');
				 	} else if (obj.success){
				 		$( '#cartitem'+ ID ).hide('slow');
				 		$.each(obj.totals, function(id, value){
	                     	amount = parseFloat(value);
	                     	$('#'+id).html(CURRENCY_SYMBOL+amount.toFixed(2));
					 	});
				 		$('#payment-amount').val(obj.charge.toFixed(2));
				 		$('#payment-amount').attr('data-amount',obj.charge.toFixed(2));
				 		$('.payment-amount').val(obj.charge.toFixed(2)).html(obj.charge.toFixed(2));
				 		CheckPaymentRequired();
				 		CheckPaymentRequired();
				 	}
	
				}catch(err){}
				$('body').css('cursor','default'); 
		    },
			error: function(jqXHR, textStatus, errorThrown){
				$( '#cartitem'+ ID ).fadeTo( "slow", 1 );
				alert(textStatus+': '+errorThrown);
				console.log('AJAX error:'+errorThrown);
				$('body').css('cursor','default'); 
	      	}
		});
	}else{
		return false;
	}
}



function AddStudent(formID){
	$('body').css('cursor', 'wait');
	$('#'+formID).find('.btn').addClass('disabled');
	var frmTkn = $("#formToken").val();
	var cnt = $("#cnt").val();
	var trial = $("#student-trial-flag").val();
	$.ajax({
		type : "POST",
		url : "/admin/includes/processes/processes-enrolment.php",
		cache : false,
		data : 'action=studentTemplate&cnt='+cnt+'&trial_flag='+trial+'&formToken='+frmTkn,
		dataType : "json",
		success : function(obj, textStatus) {
			try {
				if (obj.success){
			 		$('#student-wrapper').append(obj.template);
			 		cnt++;
			 		$("#cnt").val(cnt); 
			 	}
			} catch (err) {}
			$('body').css('cursor', 'default');
			$('#'+formID).find('.btn').removeClass('disabled');
		},
		error: function(jqXHR, textStatus, errorThrown){
			$('body').css('cursor','default'); 
			$('#'+formID).find('.btn').removeClass('disabled');
			alert(textStatus+': '+errorThrown);
			console.log('AJAX error:'+errorThrown);
	  }
	});
}



function GoToStep(VAL){
	$('body').css('cursor', 'wait');
	var previous = VAL-1;
	$('#step'+ previous +'-btn').addClass('disabled');
	$.ajax({
		type : "POST",
		url : "/admin/includes/processes/processes-enrolment.php",
		cache : false,
		data : 'action=SetStep&step='+VAL+'&formToken='+$("#formToken").val(),
		dataType : "json",
		success : function(obj, textStatus) {
			try {
				if (obj.success){
			 		$('#accordion').find('.collapse.in').removeClass('in');
			 		$('.step'+VAL).collapse('show');
			 		$('#unchecked-step'+ previous).hide();
			 		$('#checked-step'+ previous).show();
			 		$('html,body').animate({
	        			scrollTop : $('#enrolment-wrapper').offset().top
	        		});
			 		if (VAL == 2) $('#add-member-form').show();
			 		
			 	}
			} catch (err) {}
			$('body').css('cursor', 'default');
			$('#step'+ previous +'-btn').removeClass('disabled');
		},
		error: function(jqXHR, textStatus, errorThrown){
			$('body').css('cursor','default'); 
			$('#step'+ previous +'-btn').removeClass('disabled');
			alert(textStatus+': '+errorThrown);
			console.log('AJAX error:'+errorThrown);
	  }
	});
}





function setCCRequired(CONDITION) {
    if(CONDITION){
      $('.cc-req').attr('required', 'required');
      $('.cc-select-req').addClass('required');
    }else{
      $('.cc-req').removeAttr('required');
      $('.cc-select-req').removeClass('required');
    }
}

function CheckPaymentRequired(){
	var total_amount = parseFloat( $('#payment-amount').attr('data-amount') );
	if(total_amount > 0) {
		CheckPaymentMethod();
		$('#payment-methods-wrapper').show();
		$('#no-payment-required').hide();
	}else{
		setCCRequired(false);
		$('#payment-methods-wrapper').hide();
		$('#no-payment-required').show();
	}
	RefreshTotals();
}


function RefreshTotals(){
	var total_amount = parseFloat( $('#payment-amount').attr('data-amount') ).toFixed(2);
	var tocharge = parseFloat( $('#payment-amount').val() ).toFixed(2);
	if($("input[name='payment-method']:checked").val() == 'cc' && $('#surcharge').is(':visible')){
		$('#surcharge').html(CURRENCY_SYMBOL + (tocharge*0.02).toFixed(2));
		var tocharge = (tocharge*1.02).toFixed(2);
	}
	$('#cctotal').html(CURRENCY_SYMBOL + tocharge);
	$('#total').html(CURRENCY_SYMBOL + tocharge);
}

function calculatePrice(formID){
	var price = parseFloat($('#'+formID).find('.cal-price').attr('value'));
	$('#'+formID).find('.modifier').each(function(){
			price = price + parseFloat($('option:selected', this).attr('price'));
			
		});
	$('#'+formID).find('.cal-price').html(price.toFixed(2)); 
	$('#'+formID).find('.price').val(price.toFixed(2)); 
}


function SetPartialPayment(){
	var full = parseFloat($('#payment-amount').attr('data-amount')).toFixed(2);
	var charge = parseFloat($('#payment-amount').val()).toFixed(2);
	if(full != charge){
		$('#nextpayment-wrapper').show('slow');
		$('.partialpay').show('slow');
		$('#partialpayment').html(CURRENCY_SYMBOL + charge);
		$('#from-payment').attr('required','required');
	}else{
		$('#nextpayment-wrapper').hide('slow');
		$('.partialpay').hide('slow');
		$('.nextpayment').val('');
		$('#from-payment').removeAttr('required');
	}
	CheckPaymentRequired();
}

var ajaxtimestamp = null;
function RunFindMember(){
	$('body').css('cursor', 'wait');
	var query = $("#query").val();
	ajaxtimestamp = new Date().getTime();
	$.ajax({
		type : "POST",
		url : "/admin/includes/processes/processes-member.php",
		cache : false,
		data : 'action=FindMember&query='+query+'&formToken='+$("#formToken").val()+'&timestamp='+ajaxtimestamp,
		dataType : "json",
		success : function(obj, textStatus) {
			try {
				if (obj.success && ajaxtimestamp == obj.timestamp){
			 		$('#found-members').html(obj.template);
			 	}
				if(!obj.success && obj.error){
					$('#found-members').html('<h4>'+obj.error+'</h4>');
				}
			} catch (err) {}
			$('body').css('cursor', 'default');
		},
		error: function(jqXHR, textStatus, errorThrown){
			$('body').css('cursor','default'); 
			//alert(textStatus+': '+errorThrown);
			console.log('AJAX error:'+errorThrown);
	  }
	});
}
var findMemberVar;
function FindMember() {
	clearTimeout(findMemberVar);
	findMemberVar = setTimeout(function(){ RunFindMember() }, 1000);
}



function setUser(ID){
	$('body').css('cursor', 'wait');
	var query = $("#query").val();
	$.ajax({
		type : "POST",
		url : "/admin/includes/processes/processes-member.php",
		cache : false,
		data : 'action=SetExistingMember&user_id='+ID+'&formToken='+$("#formToken").val(),
		dataType : "json",
		success : function(obj, textStatus) {
			try {
				if (obj.success){
			 		$('#member-details-wrapper').html(obj.template);
			 		$('#found-members').html('');
			 	}
			} catch (err) {}
			$('body').css('cursor', 'default');
		},
		error: function(jqXHR, textStatus, errorThrown){
			$('body').css('cursor','default'); 
			alert(textStatus+': '+errorThrown);
			console.log('AJAX error:'+errorThrown);
	  }
	});
}

var running = false;
function ResendEmail(ID){
	if(!running){
		running = true;
		$('body').css('cursor', 'wait');
		var query = $("#query").val();
		$.ajax({
			type : "POST",
			url : "/admin/includes/processes/processes-email.php",
			cache : false,
			data : 'action=ReSendEmail&email_id='+ID+'&formToken='+$("#formToken").val(),
			dataType : "json",
			success : function(obj, textStatus) {
				try {
					if (obj.error) {
						$('#error').find('b').html(obj.error);
						$('#error').slideDown();
						setTimeout(function(){
							$('#error').slideUp();
				    	},10000);
				 	} else if (obj.success){
				 		$('#sent').find('b').html(obj.success);
				 		$('#sent').slideDown();
				 		setTimeout(function(){
							$('#sent').slideUp();
				    	},10000);
				 	}
				} catch (err) {}
				$('body').css('cursor', 'default');
				running = false;
			},
			error: function(jqXHR, textStatus, errorThrown){
				$('body').css('cursor','default'); 
				alert(textStatus+': '+errorThrown);
				console.log('AJAX error:'+errorThrown);
		  }
		});
	}
}

function ViewEmail(ID){
	window.open("/admin/includes/processes/view-email.php?action=ViewEmail&id="+ID);
}


function displayForm(ID){
	$('#member-details').hide('slow');
	$('#'+ID).show('slow');
}


function SelectSingleClass(ELEMENT, VALUE){
	if( $(ELEMENT).is(':checked')) { 
		$('.chckbx').removeAttr('checked');
		$('.value').val('0');
		$('.week').hide('slow');
		$(ELEMENT).attr('checked','checked');
		$(ELEMENT).parent().children('.value').val(VALUE) 
		$(ELEMENT).closest('.class-wrapper').find('.week').show('slow'); 
	}else{
		$(ELEMENT).parent().children('.value').val('0') 
		$(ELEMENT).closest('.class-wrapper').find('.week').hide('slow'); 
	}
}

function MoveEnrolmentForm(STUDENT_ID, TERM_ID, CLASS_ID, TITLE, DOB_D, DOB_M, DOB_Y,data_id){
	autoFun('#move-enrolment-wrapper');
	$('#move-student').val(STUDENT_ID);
	$('#move-term').val(TERM_ID);
	$('#move-term').closest('.form-wrapper').find('.same_term').val(TERM_ID); // FILTER BY SAME TERM
	$('#move-class').val(CLASS_ID);
	$('#move-title').html(TITLE);
	$('#student-classes-content').hide('slow');
	$('#search-classes-form-move-result').html('');
	$('#move-enrolment-wrapper').show('slow');
	$('#move-enrolment-wrapper').find('select[name="day"]').val(parseInt(DOB_D));
	$('#move-enrolment-wrapper').find('select[name="month"]').val(parseInt(DOB_M));
	$('#move-enrolment-wrapper').find('select[name="year"]').val(parseInt(DOB_Y));
	$('select.selstyle').selectric();
}

function MakeUpClassForm(STUDENT_ID, TERM_ID, CLASS_ID, TITLE, DOB_D, DOB_M, DOB_Y){
	autoFun('#make-up-wrapper');
	$('#make-up-student').val(STUDENT_ID);
	$('#make-up-term').val(TERM_ID);
	$('#make-up-term').closest('.form-wrapper').find('.same_term').val(TERM_ID); // FILTER BY SAME TERM
	$('#make-up-class').val(CLASS_ID);
	$('#make-up-title').html(TITLE);
	$('#student-classes-content').hide('slow');
	$('#search-classes-form-makeup-result').html('');
	$('#make-up-wrapper').show('slow');
	$('#make-up-wrapper').find('select[name="day"]').val(parseInt(DOB_D));
	$('#make-up-wrapper').find('select[name="month"]').val(parseInt(DOB_M));
	$('#make-up-wrapper').find('select[name="year"]').val(parseInt(DOB_Y));
	$('select.selstyle').selectric();
}

function MoveTrialClassForm(STUDENT_ID, TERM_ID, CLASS_ID, TITLE, DOB_D, DOB_M, DOB_Y, data_id){
	autoFun('#move-trial-wrapper');
	$('#move-trial-student').val(STUDENT_ID);
	$('#move-trial-term').val(TERM_ID);
	$('#move-trial-term').closest('.form-wrapper').find('.same_term').val(TERM_ID); // FILTER BY SAME TERM
	$('#move-trial-class').val(CLASS_ID);
	$('#move-trial-title').html(TITLE);
	$('#student-classes-content').hide('slow');
	$('#search-classes-form-move-trial-result').html('');
	$('#move-trial-wrapper').show('slow');
	$('#move-trial-wrapper').find('select[name="day"]').val(parseInt(DOB_D));
	$('#move-trial-wrapper').find('select[name="month"]').val(parseInt(DOB_M));
	$('#move-trial-wrapper').find('select[name="year"]').val(parseInt(DOB_Y));
	$('select.selstyle').selectric();
}

function CancelEnrolment(STUDENT_ID, TERM_ID, CLASS_ID, TYPE, WEEK){
	if(confirm('Do you want to cancel this enrolment?')){
		$('body').css('cursor', 'wait');
		$.ajax({
			type : "POST",
			url : "/admin/includes/processes/processes-enrolment.php",
			cache : false,
			data : 'action=CancelEnrolment&student_id='+STUDENT_ID+'&term_object_id='+TERM_ID+'&class_object_id='+CLASS_ID+'&enrolment_type='+TYPE+'&enrolment_week='+WEEK+'&formToken='+$("#formToken").val(),
			dataType : "json",
			success : function(obj, textStatus) {
				try {
					
					if (obj.error) {
						$('#error').find('b').html(obj.error);
						$('#error').slideDown();
						setTimeout(function(){
							$('#error').slideUp();
				    	},10000);
				 	} else if (obj.success){
				 		$('#s'+STUDENT_ID+'-t'+TERM_ID+'-c'+CLASS_ID+'-'+TYPE+'-'+WEEK).addClass('text-deleted').find('.enrolment-options').html('');
				 		$('#sent').find('b').html(obj.success);
				 		$('#sent').slideDown();
				 		setTimeout(function(){
							$('#sent').slideUp();
				    	},10000);
				 	}
				} catch (err) {}
				$('body').css('cursor', 'default');
			},
			error: function(jqXHR, textStatus, errorThrown){
				$('body').css('cursor','default'); 
				alert(textStatus+': '+errorThrown);
				console.log('AJAX error:'+errorThrown);
		  }
		});
	}
	
}


$("input[name='payment-method']").change(function() {
	CheckPaymentMethod();
});

function CheckPaymentMethod() {
	 if ($("input[name='payment-method']:checked").val() == 'cc'){
		 $('#cc-wrapper').show('slow');
		 $('.ccsurchage').show('slow');
		 setCCRequired(true);
	 }else{
		 $('#cc-wrapper').hide('slow');
		 $('.ccsurchage').hide('slow');
		 setCCRequired(false);
	 }
	 RefreshTotals();
};

function FastConvert(){
	$('#unchecked-step1').hide();
	$('#checked-step1').show();
	$('#unchecked-step2').hide();
	$('#checked-step2').show();
	$('#unchecked-step4').hide();
	$('#checked-step4').show();
	
	//$('#add-member-form').submit();
	$('#student-form').submit();
	$('#additional-form').submit();
	CheckPaymentMethod();
}


function HideNews(){
	$.ajax({
		type : "POST",
		url : "/admin/includes/processes/processes-news.php",
		cache : false,
		data : 'hide_news=true=',
		dataType : "json",
		success : function(obj, textStatus) { },
		error: function(){
			console.log('AJAX error');
	  }
	});
}

function AddWaitList(WRAPPER_ID, USER_ID, TERM_ID, CLASS_ID){
	$('body').css('cursor', 'wait');
	stdid = $('#student'+WRAPPER_ID).find('.student_id').val();
	stdname = $('#student'+WRAPPER_ID).find('.student_name').val();
	stdsurname = $('#student'+WRAPPER_ID).find('.student_surname').val();
	stddob = $('#student'+WRAPPER_ID).find('.student_dob').val();
	stdmedical = $('#student'+WRAPPER_ID).find('.student_medical').val();
	$.ajax({
		type : "POST",
		url : "/admin/includes/processes/processes-enrolment.php",
		cache : false,
		data : 'action=AddWaitList&student_id='+stdid+'&user_id='+USER_ID+'&student_name='+stdname+'&student_surname='+stdsurname+'&student_dob='+stddob+'&student_medical='+stdmedical+'&term_object_id='+TERM_ID+'&class_object_id='+CLASS_ID+'&formToken='+$("#formToken").val(),
		dataType : "json",
		success : function(obj, textStatus) {
			try {
				if (obj.error) {
					alert(obj.error);
			 	} else if (obj.success){
			 		alert(obj.success);
			 	}
			} catch (err) {}
			$('body').css('cursor', 'default');
		},
		error: function(jqXHR, textStatus, errorThrown){
			$('body').css('cursor','default'); 
			alert(textStatus+': '+errorThrown);
			console.log('AJAX error:'+errorThrown);
	  }
	});
}

function RemoveWaitList(WRAPPER_ID, WAITLIST_ID){
	$('body').css('cursor', 'wait');
	$.ajax({
		type : "POST",
		url : "/admin/includes/processes/processes-enrolment.php",
		cache : false,
		data : 'action=RemoveWaitList&waitlist_id='+WAITLIST_ID+'&formToken='+$("#formToken").val(),
		dataType : "json",
		success : function(obj, textStatus) {
			try {
				if (obj.error) {
					alert(obj.error);
			 	} else if (obj.success){
			 		$(WRAPPER_ID).hide('slow');
			 	}
			} catch (err) {}
			$('body').css('cursor', 'default');
		},
		error: function(jqXHR, textStatus, errorThrown){
			$('body').css('cursor','default'); 
			alert(textStatus+': '+errorThrown);
			console.log('AJAX error:'+errorThrown);
	  }
	});
}